package com.simpletaskapp.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.simpletaskapp.R;
import com.simpletaskapp.constants.Constants;
import com.simpletaskapp.domain.Task;
import com.simpletaskapp.persistence.TaskDAO;

public class TaskList extends ListActivity {

	private TaskDAO taskDAO;

	private List<Task> tasks = new ArrayList<Task>();

	private ArrayAdapter<Task> adapter;

	private boolean restartList = false;

	private AdView adView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list);

		taskDAO = new TaskDAO(this);
		taskDAO.open();

		adapter = (new ArrayAdapter<Task>(this, R.layout.task_list_item, tasks) {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				View row = convertView;

				if (row == null) {
					LayoutInflater inflater = getLayoutInflater();
					row = inflater.inflate(R.layout.task_list_item, null);
				}

				final Task task = getItem(position);

				final TextView description = (TextView) row
						.findViewById(R.id.task_description);
				final TextView creationDate = (TextView) row
						.findViewById(R.id.task_creation_date);
				final CheckBox done = (CheckBox) row
						.findViewById(R.id.task_done);

				done.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					private void setTextStyle(boolean isChecked) {
						int descriptionFlags = description.getPaintFlags();
						int creationDateFlags = creationDate.getPaintFlags();

						if (isChecked) {
							description.setPaintFlags(descriptionFlags
									| Paint.STRIKE_THRU_TEXT_FLAG);
							creationDate.setPaintFlags(creationDateFlags
									| Paint.STRIKE_THRU_TEXT_FLAG);
						} else {
							description.setPaintFlags(descriptionFlags
									^ Paint.STRIKE_THRU_TEXT_FLAG);
							creationDate.setPaintFlags(creationDateFlags
									^ Paint.STRIKE_THRU_TEXT_FLAG);
						}
					}

					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						task.setDone(isChecked);
						setTextStyle(isChecked);
						taskDAO.open();
						taskDAO.saveOrUpdateTask(task);
					}
				});

				description.setText(task.getDescription());
				creationDate.setText(task.getCreationDateFormatted());
				done.setChecked(task.isDone());

				return row;
			}
		});

		registerForContextMenu(getListView());
		setListAdapter(adapter);

		// ADMOB
		adView = new AdView(this, AdSize.BANNER, Constants.ADMOB_EDITOR_ID);
		LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
		layout.addView(adView);
		adView.loadAd(new AdRequest());

		String title = getString(R.string.loading);
		String message = getString(R.string.loadingTasks);

		new TaskListLoaderTask(title, message).execute();
	}

	protected void refreshList() {
		if (restartList) {
			String title = getString(R.string.refreshing);
			String message = getString(R.string.refreshingTasks);

			new TaskListLoaderTask(title, message).execute();
		} else
			restartList = true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.task_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.newTask:
			Intent intent = new Intent(this, CreateTask.class);
			Toast.makeText(this, getString(R.string.newTask),
					Toast.LENGTH_SHORT).show();
			this.startActivity(intent);
			break;
		case R.id.deletePerformedTasks:
			taskDAO.deletePerformedTasks();
			Toast.makeText(this, getString(R.string.deletePerformedTasksDone),
					Toast.LENGTH_SHORT).show();
			refreshList();
			break;
		}

		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		if (v.getId() == android.R.id.list) {
			menu.setHeaderTitle(getString(R.string.actions));
			menu.add(Menu.NONE, R.string.edit, 0,
					getString(R.string.edit));
			menu.add(Menu.NONE, R.string.delete, 1,
					getString(R.string.delete));
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();

		Task task = tasks.get(info.position);

		switch (item.getItemId()) {
		case R.string.edit:
			editTask(task);
			break;

		case R.string.delete:
			Toast.makeText(this, getString(R.string.deleted),
					Toast.LENGTH_SHORT).show();
			taskDAO.deleteTask(task);
			refreshList();
			break;
		}

		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Task task = adapter.getItem(position);
		editTask(task);
	}

	private void editTask(Task task) {
		Toast.makeText(this, getString(R.string.editTask), Toast.LENGTH_SHORT)
				.show();

		Bundle bundle = new Bundle();
		bundle.putSerializable("TASK", task);

		Intent intent = new Intent(TaskList.this, EditTask.class);
		intent.putExtras(bundle);

		startActivity(intent);
	}

	private class TaskListLoaderTask extends AsyncTask<Void, Void, List<Task>> {

		private ProgressDialog dialog;

		private String title;

		private String message;

		public TaskListLoaderTask(String title, String message) {
			this.title = title;
			this.message = message;
		}

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(TaskList.this);
			dialog.setTitle(title);
			dialog.setMessage(message);
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.show();
		}

		@Override
		protected List<Task> doInBackground(Void... params) {
			return taskDAO.getAllTasks();
		}

		@Override
		protected void onPostExecute(List<Task> result) {

			tasks.clear();
			tasks.addAll(result);
			adapter.notifyDataSetChanged();

			this.dialog.dismiss();
		}
	}

	@Override
	protected void onPause() {
		taskDAO.close();
		super.onPause();
	}

	@Override
	protected void onResume() {
		taskDAO.open();
		super.onResume();
		refreshList();
	}

	@Override
	public void onDestroy() {
		adView.destroy();
		taskDAO.close();
		super.onDestroy();
	}
}
